const { updateOrderStateSerivce } = require('../service/payment.service')
const { deleteCartService } = require('../service/cart.service')
const qs = require('qs')
const updateOrderState = async (ctx, next) => {
  // 修改订单状态为: [待支付]
  const state = '待支付'
  ctx.request.body.order = qs.parse(ctx.request.body.order)
  console.log(ctx.request.body);
  const { orderId } = ctx.request.body.order
  const res = await updateOrderStateSerivce(state, orderId)
  if (res) {
    console.log('1. 修改订单状态为: [待支付]');
    await next()
  }
}

const deleteCart = async (ctx, next) => {
  // 删除购物车中的数据: [待支付]的订单不应该出现在购物车
  const goodsData = ctx.request.body.order.goodsData
  goodsData.forEach(async item => {
    await deleteCartService(item.id)
  })
  console.log('2. 订单数据在购物车已删除');
  await next()
}

const payResultHandle = async (ctx, next) => {
  const state = ctx.state
  if (state.code === '10000') { // 接口调用成功
    switch (state.trade_status) {
      case 'WAIT_BUYER_PAY':
        ctx.body = {
          "success": true,
          "message": "success",
          "code": 200,
          "timestamp": (new Date()).getTime(),
          "result": {
            "status": 0,
            "massage": '交易创建，等待买家付款'
          }
        }
        break;
      case 'TRADE_CLOSED':
        ctx.body = {
          "success": true,
          "message": "success",
          "code": 200,
          "timestamp": (new Date()).getTime(),
          "result": {
            "status": 1,
            "massage": '未付款交易超时关闭，或支付完成后全额退款'
          }
        }
        break;
      case 'TRADE_SUCCESS':
        ctx.body = {
          "success": true,
          "message": "success",
          "code": 200,
          "timestamp": (new Date()).getTime(),
          "result": {
            "status": 2,
            "massage": '交易支付成功'
          }
        }
        // 订单状态修改为[已付款]
        await updateOrderStateSerivce('已支付', ctx.request.body.out_trade_no)
        break;
      case 'TRADE_FINISHED':
        ctx.body = {
          "success": true,
          "message": "success",
          "code": 200,
          "timestamp": (new Date()).getTime(),
          "result": {
            "status": 3,
            "massage": '交易结束，不可退款'
          }
        }
        await updateOrderStateSerivce('交易结束', ctx.request.body.out_trade_no)
        break;
    }
  } else if (state.code === '40004') {
    await updateOrderStateSerivce('交易失败', ctx.request.body.out_trade_no)
    ctx.body = {
      msg: '交易失败'
    }
  }
}

module.exports = {
  updateOrderState,
  deleteCart,
  payResultHandle
}